﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace Oridea.Data.Fetching {
	public class CollectionFetcher<T> : IOrderableFetcher<T> {
		private readonly IQueryable<T> _query;
		private int? _cachedCount;

		public CollectionFetcher(IQueryable<T> query) {
			if (query == null) {
				throw new ArgumentNullException("query");
			}

			_query = query;
		}

		protected IQueryable<T> Query {
			get { return _query; }
		}

		public IPagingFetcher<T> OrderBy(OrderingSequence<T> orderingSequence) {
			if (orderingSequence == null) {
				throw new ArgumentNullException("orderingSequence");
			}

			return new PagingCollectionFetcher<T>(orderingSequence.ApplyTo(_query));
		}

		public ReadOnlyCollection<T> Fetch() {
			List<T> fetchedCollection = _query.ToList();
			_cachedCount = fetchedCollection.Count;
			return fetchedCollection.AsReadOnly();
		}

		public int Count() {
			return _cachedCount ?? (_cachedCount = _query.Count()).Value;
		}
	}
}
